package cn.touna.jss.modules.adapter;

import cn.touna.jss.common.entity.FileRequestEntity;
import cn.touna.jss.common.exception.ResponseException;
import cn.touna.jss.common.mq.KafkaComponent;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.entity.RequestEntity;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.risk.api.exception.BusinessException;
import cn.touna.risk.api.exception.ServiceException;
import cn.touna.risk.api.utils.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.util.TypeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 请求分发器
 * Created by wuwc on 2017/12/1.
 *
 *  CommandLineRunner  Override run()
 *  springboot 启动完成后：回调run()方法
 */
@Service
public class GatewayHanlder implements ApplicationContextAware, InitializingBean, CommandLineRunner {
    private static final Logger logger = LogManager.getLogger(GatewayHanlder.class);

    private ApiFactory apiFactory;
    @Autowired
    private KafkaComponent kafkaComponent;

    final ParameterNameDiscoverer parameterUtil;

    public GatewayHanlder() {
        parameterUtil = new LocalVariableTableParameterNameDiscoverer();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        apiFactory.loadApiBeans();
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        apiFactory = new ApiFactory(context);
    }

    @Override
    public void run(String... strings) throws Exception {
        syncApiMessage();
    }

    /***
     * 发送消息，同步对外暴露接口信息至OPS
     */
    public void syncApiMessage(){
        kafkaComponent.sendApiMessage(apiFactory.getApiMap());
    }

    /**
     * 处理非文件流类型
     *
     * @param requestEntity
     * @param request
     * @param <T>
     * @return
     */
    public <T> Response<T> hanldPost(RequestEntity requestEntity, HttpServletRequest request) {
        String apiMethod = null;
        try {
            apiMethod = ApiUtils.genApiMethod(requestEntity);
            ApiFactory.ApiRunnable apiRunnable = getApiMethod(apiMethod);
            Object[] args = buildParams(apiRunnable, requestEntity.getParams(), request, null, requestEntity.getFile());
            Object result = apiRunnable.run(args);
            return ApiUtils.hanldReturnResult(result);
        } catch (ResponseException e) {
            return e.getResponse();
        } catch (BusinessException e) {
            return ApiUtils.handError(e, apiMethod);
        } catch (ServiceException e) {
            return ApiUtils.handError(e, apiMethod);
        } catch (InvocationTargetException e) {
            Throwable t = e.getTargetException();
            return ApiUtils.handError(t, apiMethod);
        } catch (Exception e) {
            return ApiUtils.handError(e, apiMethod);
        }
    }

    /**
     * 处理文件流请求
     *
     * @param requestEntity
     * @param request
     * @param <T>
     * @return
     */
    public <T> Response<T> hanldFilePost(FileRequestEntity requestEntity, HttpServletRequest request) {
        String apiMethod = null;
        try {
            apiMethod = ApiUtils.genApiMethod(requestEntity);
            ApiFactory.ApiRunnable apiRunnable = getApiMethod(apiMethod);
            Object[] args = buildParams(apiRunnable, JSONUtil.getJSONObject(requestEntity.getBizContent()),
                    request, requestEntity.getUploadFile(), null);
            Object result = apiRunnable.run(args);
            return ApiUtils.hanldReturnResult(result);
        } catch (ResponseException e) {
            return e.getResponse();
        } catch (BusinessException e) {
            return ApiUtils.handError(e, apiMethod);
        } catch (ServiceException e) {
            return ApiUtils.handError(e, apiMethod);
        } catch (InvocationTargetException e) {
            Throwable t = e.getTargetException();
            return ApiUtils.handError(t, apiMethod);
        } catch (Exception e) {
            return ApiUtils.handError(e, apiMethod);
        }
    }

    /**
     * 校验方法合法性
     *
     * @param apiMethod
     * @return
     * @throws ServiceException
     */
    private ApiFactory.ApiRunnable getApiMethod(String apiMethod) throws ResponseException {
        ApiFactory.ApiRunnable apiRunnable = apiFactory.getApiRunnable(apiMethod);
        if (apiRunnable == null) {
            logger.error(apiMethod+"接口不存在！");
            throw ResponseException.build(SystemErrorCodeEnum.JSS_PARAM_CHECK_FAILED, apiMethod+"接口不存在！");
        }
        return apiRunnable;
    }

    /**
     * 构造接口参数
     *
     * @param apiRun
     * @param params
     * @param request
     * @return
     * @throws ServiceException
     */
    private Object[] buildParams(ApiFactory.ApiRunnable apiRun, JSONObject params, HttpServletRequest request, MultipartFile uploadFile, byte[] file) throws ServiceException {
        Method method = apiRun.getTargetMethod();
        Class<?>[] paramTypes = method.getParameterTypes();
        Object[] args = new Object[paramTypes.length];
        Annotation[][] annos = method.getParameterAnnotations();
        for (int i = 0; i < paramTypes.length; i++) {
            if (paramTypes[i].isAssignableFrom(HttpServletRequest.class)) {
                args[i] = request;
            } else if (paramTypes[i].isAssignableFrom(MultipartFile.class)) {
                args[i] = uploadFile;
            } else if (paramTypes[i].isAssignableFrom(byte[].class)) {
                args[i] = file;
            } else {
                //对于使用注解@RequestParam的参数，实施注入
                boolean needContinue = false;
                for (Annotation anno : annos[i]) {
                    if (anno instanceof RequestParam) {
                        RequestParam requestParam = (RequestParam) anno;
                        if (!StringUtils.isEmpty(requestParam.value())) {
                            args[i] = TypeUtils.cast(params.get(requestParam.value()), paramTypes[i], ParserConfig.getGlobalInstance());
                            needContinue = true;
                            break;
                        }
                    }
                }
                if (needContinue)
                    continue;
                if (null != params) {
                    if (!isJavaClass(paramTypes[i])) {
                        args[i] = JSONUtil.jsonToObject(params, paramTypes[i]);
                    } else {
                        args[i] = params.toJSONString();
                    }
                } else {
                    args[i] = params;
                }
            }
        }
        return args;
    }

    private static boolean isJavaClass(Class<?> clz) {
        return clz != null && clz.getClassLoader() == null;
    }


}
